<template>
  <div class="add-enterprise">
    <header class="add-header">
      <div class="left">
        <span
          class="arrow"
          @click="$router.back()"
        ><i class="el-icon-arrow-left" />返回</span>
        <span>|</span>
        <span>{{ id? '编辑' : '添加' }}企业</span>
      </div>
      <div class="right">蓝景程序员</div>
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form
            ref="ruleForm"
            label-width="100px"
            :model="addForm"
            :rules="addRules"
          >
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <!-- v-model的值为当前被选中的el-option的 value 属性值 -->
              <el-select v-model="addForm.industryCode">
                <el-option
                  v-for="item in industryList"
                  :key="item.industryCode"
                  :label="item.industryName"
                  :value="item.industryCode"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" />
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseId">
              <el-upload
                ref="uploadFile"
                action="#"
                :http-request="uploadRequest"
                :before-upload="onBeforUpload"
                :on-remove="onRemove"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过5000kb
                </div>
              </el-upload>
              <!-- 准备img标签 -->
              <img v-if="addForm.businessLicenseUrl" :src="addForm.businessLicenseUrl" alt="" class="img">
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="onReset">重置</el-button>
        <el-button type="primary" @click="onSubmit">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import { addEnterPriseAPI, getEnterPriseDetailAPI, getIndustryListAPI, updateEnterPriseDetailAPI, uploadAPI } from '@/api/enterprise'
export default {
  name: 'AddEnterPrise',
  data() {
    return {
      // 添加企业
      addForm: {
        name: '', // 企业名称
        legalPerson: '', // 法人
        registeredAddress: '', // 注册地址
        industryCode: '', // 所在行业
        contact: '', // 企业联系人
        contactNumber: '', // 联系人电话
        businessLicenseUrl: '', // 营业执照url
        businessLicenseId: '' // 营业执照id
      },
      industryList: [], // 保存行业列表数据
      // 表单校验的规则
      addRules: {
        name: [{ required: true, message: '企业名称为必填', trigger: 'blur' }],
        legalPerson: [
          { required: true, message: '法人为必填', trigger: 'blur' }
        ],
        registeredAddress: [
          { required: true, message: '注册地址为必填', trigger: 'blur' }
        ],
        industryCode: [
          { required: true, message: '所在行业为必填', trigger: 'change' }
        ],
        contact: [
          { required: true, message: '企业联系人为必填', trigger: 'blur' }
        ],
        contactNumber: [
          { required: true, message: '企业联系人电话为必填', trigger: 'blur' },
          { pattern: /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/, message: '手机号码不合法', trigger: 'blur' }
        ],
        businessLicenseId: [
          { required: true, message: '请上传营业执照', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    id() {
      return this.$route.params.id
    }
  },
  created() {
    this.getIndustryList()
    // 判断 如果 有 id 属性 计算属性
    if (this.id) {
      this.getEnterPriseDetail()
    }
  },
  methods: {
    // 获取企业的详情信息
    async getEnterPriseDetail() {
      try {
        const res = await getEnterPriseDetailAPI(this.id)
        const { name, id, legalPerson, registeredAddress, industryCode, businessLicenseUrl, businessLicenseId, contact, contactNumber } = res.data
        this.addForm = { name, id, legalPerson, registeredAddress, industryCode, businessLicenseUrl, businessLicenseId, contact, contactNumber }
      } catch (error) {
        if (error.response) {
          this.$message.error(error.response.data.msg)
        }
      }
    },
    // 表单重置
    onReset() {
      // 调用表单重置的方法
      this.$refs.ruleForm.resetFields()
      // 手动将 addForm里面的 businessLicenseUrl 清空
      this.addForm.businessLicenseUrl = ''
      // 调用 el-upload 组件里面的 clearFiles方法
      this.$refs.uploadFile.clearFiles()
    },
    // 表单提交
    onRemove() {
      // console.log('图片被删除了')
      // 将 addForm 里面的 businessLicenseId 和 businessLicenseUrl 清空
      this.addForm.businessLicenseId = ''
      this.addForm.businessLicenseUrl = ''
      this.$refs.ruleForm.validateField('businessLicenseId')
      // console.log(this.addForm)
    },
    async onSubmit() {
      // 兜底校验
      await this.$refs.ruleForm.validate()
      try {
        if (this.id) {
          // 编辑
          await updateEnterPriseDetailAPI(this.addForm)
          this.$message.success('编辑企业成功')
        } else {
          // 添加
          await addEnterPriseAPI(this.addForm)
          this.$message.success('添加企业成功')
        }

        this.$router.back()
      } catch (error) {
        if (error.response) {
          this.$message.error(error.response.data.msg)
        }
      }
    },
    // 上传文件前对文件的格式与文件的大小进行校验
    onBeforUpload(file) {
      // console.log(file.type)
      // 只允许：jpg / png 这两种图片格式
      const fileType = ['image/jpeg', 'image/jpg', 'image/png']
      // 方法用来判断一个数组是否包含一个指定的值，根据情况，如果包含则返回 true，否则返回 false。
      const isType = fileType.includes(file.type)
      if (!isType) {
        this.$message.error('上传图片只能是 PNG/JPG/JPEG 格式!')
      }
      // 文件的大小 文件不能超过5M 1M = 1024kb  1kb = 1024字节
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isLt5M) {
        this.$message.error('上传图片大小不能超过 5MB!')
      }

      return isType && isLt5M
    },
    // 获取行业列表
    async getIndustryList() {
      try {
        const res = await getIndustryListAPI()
        // console.log(res)
        this.industryList = res.data
      } catch (error) {
        if (error.response) {
          this.$message.error(error.response.data.msg)
        }
      }
    },
    // 上传文件
    async uploadRequest({ file }) {
      // console.log(file)
      // 实例化 fd 对象
      const fd = new FormData()
      fd.append('file', file)
      fd.append('type', 'businessLicense')
      // 调用封装的接口函数
      try {
        const res = await uploadAPI(fd)
        // 将上传后的图片的id与url地址保存到 addForm 对象里面
        this.addForm.businessLicenseId = res.data.id
        this.addForm.businessLicenseUrl = res.data.url
        // 文件已经上传了 对表单里面单独的字段进行校验
        this.$refs.ruleForm.validateField('businessLicenseId')
      } catch (error) {
        if (error.response) {
          this.$message.error(error.response.data.msg)
        }
      }
    }
  }
}
</script>

<style scoped lang="scss">
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }
      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;
      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }
      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;
        .el-form {
          display: flex;
          flex-wrap: wrap;
          .el-form-item {
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
  .img {
    width: 150px;
    border-radius: 5px;
  }
}
</style>
